package com.zj.utils;

import com.xkcoding.http.support.HttpHeader;
import com.zj.utils.bean.HttpConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xi.yang
 * @create 2019-05-20 13:39
 **/
public class HttpUtil {
    /**
     * 设置超时和代理
     * 这是个全局的配置
     * @param httpConfig
     */
    public static void setProxy(HttpConfig httpConfig) {
        com.xkcoding.http.HttpUtil.setConfig(com.xkcoding.http.config.HttpConfig.builder().proxy(httpConfig.getProxy()).timeout(httpConfig.getTimeout()).build());
    }

    /**
     * get请求
     * @param url
     * @param headers
     * @param forms
     * @return
     */
    public static String get(String url, Map<String, String> headers, Map<String, String> forms) {
        if (null == headers && null == forms) {
            return com.xkcoding.http.HttpUtil.get(url);
        }
        return com.xkcoding.http.HttpUtil.get(url, forms, new HttpHeader(headers), false);
    }

    /**
     * form表单的post请求
     * @param url
     * @param headers
     * @param forms
     * @return
     */
    public static String post(String url, Map<String, String> headers, Map<String, String> forms) {
        if (null == headers && null == forms) {
            return com.xkcoding.http.HttpUtil.post(url);
        }
        return com.xkcoding.http.HttpUtil.post(url, forms, new HttpHeader(headers), false);
    }

    /**
     * post请求，传入对象会转换为json
     * @param url
     * @param headers
     * @param body
     * @return
     */
    public static String post(String url, Map<String, String> headers, Object body) {
        if (headers == null) {
            return com.xkcoding.http.HttpUtil.post(url, JsonUtil.toString(body));
        }
        return com.xkcoding.http.HttpUtil.post(url, JsonUtil.toString(body), new HttpHeader(headers));
    }

    /**
     * 从浏览器复制的header或form信息转成map
     * @param mapStr
     * @return
     */
    public static Map<String, String> getMapFromString(String mapStr) {
        Map<String, String> map = new HashMap<>();
        for (String str : mapStr.split("\n")) {
            String[] kv = str.split(": ");
            map.put(kv[0], kv[1]);
        }
        return map;
    }
}
